package baseTest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class merge {
    public static void main(String[] args) {
        int[][] res = {{1,4},{4,5}};
        int[][] process = process(res);
        for (int[] r:process) {
            Arrays.stream(r).forEach(System.out::print);
        }
    }
    public static int[][] process(int[][] intervals){
        if (intervals.length <= 1){
            return intervals;
        }
        List<Integer> resultBegin = new ArrayList<>();
        List<Integer> resultEnd = new ArrayList<>();
        int[] begins = new int[intervals.length];
        int[] ends = new int[intervals.length];
        for (int i = 0; i < intervals.length; i++) {
            begins[i] = intervals[i][0];
            ends[i] = intervals[i][1];
        }
        Arrays.sort(begins);
        Arrays.sort(ends);

        int second = ends[0];
        resultBegin.add(begins[0]);
        int n = 0;
        for (int i = 1; i < begins.length; i++) {
            if (begins[i] >= second){
                resultEnd.add(second);
                resultBegin.add(begins[i]);
            }
                second = ends[i];
        }
        resultEnd.add(second);
        int[][] results = new int[resultBegin.size()][2];
        for (int i = 0; i < resultBegin.size(); i++) {
            results[i][0] = resultBegin.get(i);
            results[i][1] = resultEnd.get(i);
        }
        return results;
    }
}
